<!--  -->
<template>
  <div style="padding-top:100px">
    <div class="app-title-container title-position">
      <modules-title :titleName="auditData.Flow.Name">
        <template slot="btn">
          <el-button class="filter-item" plain="" size="small" @click="handleBack">返回
          </el-button>
          <!-- <el-button type="primary" size="small" @click="handlUndo('ApprovalCheck')"
            v-if="form.apply_check.Cancelable">
            撤销
          </el-button>
          <el-button type="primary" size="small" @click="handlUndo('RepealCheck')"
            v-if="form.undo_check && form.undo_check.Cancelable">
            撤销
          </el-button>
          <el-button type="primary" size="small"
            v-hasPermi="{v:['sampleInspection:dealWith:and'],isF:((form.inspection_status === 0 || form.inspection_status === 3) && isAudit )}"
            @click="handlAnd()">
            审批
          </el-button> -->
          <approval :affair.sync="auditData" :is-text="false" @refresh="refreshData"
                    @submit="onSubmit" @toEdit="toEdit" @cancel="onCancel">
            <template slot="next" v-if="$route.query.type === 'ApprovalCheck'">
              <el-form ref="auditForm" :model="auditForm" :rules="rulesNum" label-width="120px">
                <el-form-item label="送检量" prop="sample_num">
                  <el-input v-model="auditForm.sample_num" @change="handlNum" placeholder="请输入送检量"></el-input>
                </el-form-item>
              </el-form>
            </template>
          </approval>
        </template>
      </modules-title>
    </div>

    <div style="padding:20px">
      <item-title title="基础数据" :borderShow="false"/>
      <ruleForm :form="form"/>
      <item-title title="审批记录" :borderShow="false"/>
      <comment-view :datas="auditData"/>

    </div>
    <el-dialog :title="titleName" :visible.sync="open" width="600px" append-to-body
               :before-close="cancel" :close-on-click-modal="false" v-if="open">
      <el-form ref="formOpen" :model="formOpen" :rules="rules" label-width="100px" size="small">

        <el-form-item label="审批结果">
          <el-radio-group v-model="formOpen.check_status">
            <el-radio v-for="(item,index) in buttonList" :key="index" :label="item.Type">
              {{item.Name}}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="审批意见">
          <el-input type="textarea" :rows="2" v-model="formOpen.check_advice"
                    placeholder="请输入审批意见"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button plain size="small" @click="cancel">取 消
        </el-button>
        <el-button size="small" type="primary" @click="submitForm">
          确定
        </el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
  import {
    viewQuality,
    flowDetail,
    applyCheck,
    undoCheck,
    applyUndo
  } from '@/api/sampleInspection'

  export default {
    components: {
      ruleForm: () => import('../modules/ruleForm')
    },
    data() {
      let CheckNum = (rule, value, callback) => {
        const rr = /(^$)|^[0-9]+(.[0-9]{1,3})?$///保留一位小数
        if (value === '') {
          callback(new Error('输入不能为空'))
        } else if (!rr.test(value)) {
          callback(new Error('只能输入整数或者保留三位小数'))
        } else {
          if (this.form.targetId == 0) {
            callback()
          } else {
            if (value > this.form.batch_num) {
              callback(new Error('送检量大于库存'))
            } else {
              callback()
            }
          }
        }
      }
      return {
        title: '详情',
        left: 'left',
        form: null,
        auditData: {
          Flow: {}
        },
        auditButtonName: '审批',
        isAudit: false,
        userInfo: null,
        open: false,
        formOpen: {
          check_advice: '',
          check_status: 'Next'
        },
        auditForm: {
          sample_num: null
        },
        rules: {
          check_advice: [
            { required: true, message: '请输入审批意见', trigger: 'blur' }
          ]
        },
        rulesNum: {
          sample_num: [{ required: true, validator: CheckNum }]
        },
        titleName: '请验审批',
        buttonList: []
      }
    },
    //是计算属性，也可以理解为一个方法。
    computed: {},
    //属性是手动定义的所需监听的值
    watch: {},
    //生命周期 - 创建完成（访问当前this实例）
    created() {
      this.detailData()
      this.userInfo = this.$store.getters.userInfo
      if (this.$route.query) {
        this.getAuditData(this.$route.query.f_id)
      }
    },
    //生命周期 - 挂载完成（访问DOM元素）
    mounted() {
    },
    //是Vue实例对象上绑定的方法，供当前Vue组件作用域内使用，
    methods: {
      //获取详情
      detailData() {
        flowDetail(this.$route.query.f_id).then(res => {
          if (res.code === 200) {
            this.form = res.data || []
            if (
              this.form.inspection_status === 3 ||
              this.form.inspection_status === 4
            ) {
              this.titleName = '撤销请验审批'
            } else {
              this.titleName = '请验审批'
            }
            if (
              this.form.quality_standard_file &&
              this.form.quality_standard_file.length > 0 &&
              this.form.quality_standard_id
            ) {
              viewQuality(this.form.quality_standard_id).then(res => {
                if (res.code === 200) {
                  this.form.quality_standard_file = res.data.file || []
                }
              })
            }
          }
        })
      },

      handlNum(val) {
        this.auditForm.sample_num = Number(val)
      },

      //返回
      handleBack() {
        this.$route.params.refresh = true
        this.$router.go(-1)
      },

      getAuditData(id) {
        this.$api.PROJECT_START_CHECK_DETAIL(id).then(res => {
          if (res.code === 200) {
            this.auditData = res.data
            console.log(this.auditData, '----------------')
            this.getButton()
          }
        })
      },
      getButton() {
        if (
          this.auditData.State !== 'Done' ||
          this.auditData.State !== 'Refuse'
        ) {
          if (this.auditData.Next && this.auditData.Next.length) {
            for (let i = 0; i < this.auditData.Next.length; i++) {
              const data = this.auditData.Next[i]
              const index = data.Staffs.findIndex(
                a => a === this.userInfo.user.id
              )
              if (index !== -1) {
                this.isAudit = true
                this.auditButtonName = data.ItemName
                this.buttonList = data.Buttons || []
                let sss = this.buttonList.findIndex(a => a.Type == 'Cancel')
                if (sss !== -1) {
                  this.buttonList.splice(sss, 1)
                }
                break
              }
            }
          }
        }
      },

      cancel() {
        this.formOpen = {
          check_advice: '',
          check_status: 1
        }
        this.open = false
      },
      submitForm() {
        this.$refs.formOpen.validate(valid => {
          if (valid) {
            let commit = undefined,
              data = {},
              msg = ''
            if (this.form.inspection_status === 0) {
              commit = applyCheck
            } else if (this.form.inspection_status === 3) {
              commit = undoCheck
            }
            data = {
              id: this.form.id,
              check_status: this.formOpen.check_status,
              check_advice: this.formOpen.check_advice
            }
            msg = '审批成功'
            commit(data).then(res => {
              if (res.code === 200) {
                this.$message.success(msg)
                this.cancel()
                this.detailData()
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {
            return false
          }
        })
      },
      refreshData() {
        this.detailData()
      },
      toEdit(affairs) {
        this.$router.push({
          path: '/sampleInspection/applied/createTest',
          query: { s_id: this.form.id }
        })
        //this.$message.warning("暂无此功能");
      },
      // affairsId, stepId , type  //选择类型, template //备注, RejectStepId  //步骤id
      onSubmit(affairsId, stepId, type, template, RejectStepId, callback) {
        console.log(affairsId, stepId, type, template, RejectStepId)
        const subdata = {
          id: this.form.id,
          check_status: type,
          check_advice: template.Remark,
          step_id: RejectStepId,
          Files: template.Files
        }
        let commit = undefined
        if (this.form.inspection_status === 0) {
          commit = applyCheck
        } else if (this.form.inspection_status === 3) {
          commit = undoCheck
        }
        if (type === 'Next') {
          subdata.sample_num = this.auditForm.sample_num
        }

        if (type === 'Next' && this.$route.query.type === 'ApprovalCheck') {
          this.$refs['auditForm'].validate((valid) => {
            if (valid) {
              this.resolutionEvaluateOperation(commit, subdata, callback)
            }
          })
        } else {
          this.resolutionEvaluateOperation(commit, subdata, callback)
        }

      },

      resolutionEvaluateOperation(commit, subdata, callback) {
        commit(subdata).then(res => {
          if (res.code === 200) {
            this.$message.success('审批成功')
            this.detailData()
            this.getAuditData(this.$route.query.f_id)
            callback(true)
          } else {
            this.$message.error(res.msg)
          }
        })
      },

      onCancel(affairsId, stepId, type, template, RejectStepId, callback) {
        let a = ''
        if (this.form.inspection_status === 3) {
          a = 'RepealCheck'
        } else {
          a = 'ApprovalCheck'
        }
        const subdata = {
          flow_id: this.$route.query.f_id,
          model_type: a
        }
        this.$comFun.cancelFunc(subdata)
          .then(() => {
            callback(true)
            this.$message({
              type: 'success',
              message: '已撤销'
            })
            this.detailData()
            this.getAuditData(this.$route.query.f_id)
            callback(true)
          })
          .catch(err => {
            this.$message.error(err)
          })
      }
    }
  }
</script>
<style scoped>
  /* @import url(); 引入css类 */
  .el-row {
    display: flex;
    justify-content: flex-start;
    flex-flow: wrap;
  }

  ::v-deep .box_card {
    border: none !important;
  }
</style>
